package org.kiwi.util;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * @email jack.liu.19910921@gmail.com
 * Created by jack on 17/7/28.
 */
public class Utils {

    public static final String PATTERN_YYYY_MM_DD_HH_MM_SS = "yyyyMMddhhmmss";
    public static final String PATTERN_YYYY_MM_DD = "yyyyMMdd";

    public static String avoidNull(String str) {
        if (null == str) {
            return "";
        }
        return str;
    }

    public static BigDecimal avoidNullWithZero(BigDecimal value) {
        if (value == null) {
            return BigDecimal.ZERO;
        }
        return value;
    }

    public static String getYesterday(String pattern) {
        return getPreviousDay(1, pattern);
    }

    public static String getPreviousDay(int previousDays, String pattern) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -previousDays);
        Date time = cal.getTime();
        return new SimpleDateFormat(pattern).format(time);
    }

    public static String format(Date date, String pattern) {
        if (date == null)
            return "";

        try {
            return new SimpleDateFormat(pattern).format(date);
        } catch (Exception e) {
            return "";
        }
    }

    public static Date parse(String date, String pattern) {
        if (isBlank(date))
            return null;

        try {
            return new SimpleDateFormat(pattern).parse(date);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取指定日期0点时间
     *
     * @param date
     * @return
     */
    public static Date getWholePoint0(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(date.getTime());
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获取指定日期24点时间
     *
     * @param date
     * @return
     */
    public static Date getWholePoint24(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(date.getTime());
        cal.set(Calendar.HOUR_OF_DAY, 24);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }
}
